package com.vitabuybuy.tv.ui.mine.address

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityAddressBinding
import com.vitabuybuy.tv.dto.AddressListDto
import com.vitabuybuy.tv.ui.mine.address.viewmodel.AddressViewModel

class AddressActivity : BaseActivity<AddressViewModel, ActivityAddressBinding>(){

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, requestCode: Int) {
            mContext.startForResult(
                bundleOf(Pair("requestCode", requestCode)),
                requestCode,
                AddressActivity::class.java
            )
        }
    }

    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_address

    private var requestCode :Int?= -1

    override fun onGetBundle(bundle: Bundle?) {
        requestCode = bundle?.getInt("requestCode")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.deliver_address_1))
        mBinding.apply {
            mViewModel = viewModel
        }
        mTvRight.apply {
            text = getString(R.string.add_new_address)
            visibility = View.VISIBLE
            setOnClickListener {
                EditAddressActivity.openActivity(
                    mContext,
                    null
                )
            }
        }
    }

    override fun observeData() {
        viewModel.getDataList()
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 10001) {
            viewModel.getDataList()
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            4 -> {
                EditAddressActivity.openActivity(
                    mContext,
                    msg.obj as AddressListDto
                )
            }
            6 -> {
                if (requestCode == 10001) return
                val intent = Intent()
                intent.putExtras(bundleOf(Pair("addressDto", msg.obj as AddressListDto)))
                finishResult(intent)
            }
        }
    }
}
